<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-finance create-page-container">
    <Title :title="title" font-size="16px" style="margin-bottom: 16px;"/>
    <el-form ref="editFinanceForm" :model="editFinanceForm" :rules="editFinanceRules" :label-position="formAlign" class="lineHeightFlex" label-width="110px">
      <el-row type="flex" class="response-el-row">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="付款人名称" prop="payName">
            <!-- allow-create -->
            <el-select
              v-model="editFinanceForm.payName"
              :remote-method="clientNameList"
              placeholder="请输入实际的付款人名称"
              size="small"
              filterable
              remote
              class="filterableSelect remoteRequest1"
              popper-class="global-select-down createDayAccountwidth240"
              default-first-option
              @change="getPayName">
              <el-option
                v-for="(item, index) in clientName"
                :key="item.id + item.value + index"
                :label="item.value"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="付款账号" prop="payNumber">
            <el-input v-model.trim="editFinanceForm.payNumber" name="payNumber" type="text" placeholder="请输入付款账号" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="付款人类型" prop="clientType">
            <el-select v-model="editFinanceForm.clientType" name="clientType" popper-class="global-select-down" size="small">
              <el-option
                v-for="item in clientTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="收入金额(元)" prop="incomeAmount">
            <el-input
              v-model="editFinanceForm.incomeAmount"
              name="incomeAmount"
              type="text"
              placeholder="请输入收入金额"
              size="small"
              @input="keyupEvent"
              @mousewheel.native.prevent/>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="交易单号" prop="transactionNumber">
            <el-input v-model.trim="editFinanceForm.transactionNumber" name="transactionNumber" type="text" size="small" placeholder="如支付宝或银行的交易单号" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="到账日期" prop="arrivalTime">
            <el-date-picker v-model="editFinanceForm.arrivalTime" :clearable="false" :editable="false" type="date" size="small" value-format="timestamp" format="yyyy/MM/dd" placeholder="选择日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="付款方式" prop="payWay">
            <el-select v-model="editFinanceForm.payWay" popper-class="global-select-down" name="payWay" size="small">
              <el-option
                v-for="item in payOption"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="类型" prop="flowType" class="is-required">
            <el-select v-model="editFinanceForm.flowType" popper-class="global-select-down" name="flowType" size="small">
              <el-option
                v-for="item in flowTypeOption"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="所属部门" prop="attributionMatrix">
            <el-cascader
              v-model="editFinanceForm.departmentId"
              :show-all-levels="false"
              :options="attributionMatrixList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: false,
              }"
              filterable
              class="width240"
              placeholder="请选择"
              size="small"
            >
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="备注" prop="remark" class="content">
            <el-input
              v-model.trim="editFinanceForm.remark"
              name="remark"
              resize="none"
              type="textarea"
              placeholder="请输入备注，限制500个字"
              maxlength="500"
              size="small" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="loading" type="primary" size="small" @click="toSave('editFinanceForm')">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="toClear()">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import { addFinance, editFinance, getFinance } from '@/api/finance';
import { getClientName, getPayOption } from '@/api/select';
import Title from '@/components/Title';
import { getDepartmentAll } from '@/api/config';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import mobileCreate from '@/mixins/mobileCreate';
export default {
  components: { Title, selectWithoutHttp },
  mixins: [mobileCreate],
  data() {
    return {
      title: '新增流水单',
      editFinanceForm: {
        payName: '',
        payNumber: '',
        clientType: '',
        incomeAmount: '',
        transactionNumber: '',
        arrivalTime: '',
        payWay: '',
        remark: '',
        flowType: 0,
        departmentId: ''
      },
      attributionMatrixList: [],
      editFinanceRules: {
        payName: [{ required: true, trigger: 'change', message: '请选择付款人名称' }],
        payNumber: [{ required: true, trigger: 'blur', message: '请输入付款账号' }],
        clientType: [{ required: true, trigger: 'change', message: '请选择付款人类型' }],
        incomeAmount: [{ required: true, trigger: 'blur', message: '请输入收入金额' }],
        transactionNumber: [{ required: true, trigger: 'blur', message: '请输入交易单号' }],
        arrivalTime: [{ required: true, trigger: 'change', message: '请输入到账日期' }],
        payWay: [{ required: true, trigger: 'change', message: '请选择付款方式' }]
      },
      clientTypeOption: [{ value: 0, label: '公司' }, { value: 1, label: '个人' }],
      payOption: [],
      flowTypeOption: [{ id: 0, name: '普通' }, { id: 1, name: '对抵' }],
      financeId: '',
      financeData: {
        payName: '',
        payNumber: '',
        clientType: '',
        incomeAmount: '',
        transactionNumber: '',
        arrivalTime: '',
        payWay: '',
        remark: '',
        departmentId: '',
        flowType: ''
      },
      loading: false,
      clientName: [],
      payName: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  created() {
    this.financeId = Number(this.$route.params.dayAccountId) || '';
    if (this.financeId) {
      this.title = '编辑流水单';
      this.getInfo();
    } else {
      this.title = '新增流水单';
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        this.editFinanceForm.departmentId = this.userInfo.deptName[0].id;
      }
    }
    this.clientNameList();
    this.payOptionList();
    this.loadResourceSelect();
    window.removeReadOnly();
    window.remoteRequest('.remoteRequest1', this.clientNameList);
  },
  methods: {
    getInfo() {
      const params = Object.create(null);
      params.ids = this.financeId;
      params.writeOffType = 0;
      getFinance(params).then(res => {
        this.editFinanceForm = res.data;
        this.editFinanceForm.incomeAmount = this.editFinanceForm.incomeAmount / 100;
        this.editFinanceForm.arrivalTime = this.editFinanceForm.arrivalTime * 1000;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    // 获取客户名称列表
    clientNameList(query = null) {
      const param = {
        clientName: query,
        isGetMengliClient: true
      };
      getClientName(param).then(res => {
        this.clientName = res.data;
        // 将输入内容创建为条目
        if (query && (res.data.length === 0 || query !== res.data[0].value)) {
          const item = {
            value: query,
            id: 0,
            clientType: 0
          };
          this.clientName.unshift(item);
        }
      }, result => {
        this.$message.error(result.message);
      });
    },
    // 获取付款方式列表
    payOptionList() {
      getPayOption().then(res => {
        this.payOption = res.data;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    getPayName(val) {
      this.payName = val;
      if (typeof this.payName === 'number') {
        const payName = this.clientName.find(valitem => valitem.id === this.payName);
        this.financeData.payName = payName.value;
        this.editFinanceForm.payName = payName.value;
      } else {
        this.financeData.payName = this.payName;
        this.editFinanceForm.payName = this.payName;
      }
    },
    add() {
      addFinance(this.financeData).then(res => {
        this.loading = false;
        this.$message.success('添加成功');
        this.time = Date.parse(new Date()) / 1000;
        this.$router.push({
          name: 'dayAccount'
        });
      }, result => {
        this.loading = false;
        // this.$message.error(result.message);
      });
    },
    edit() {
      editFinance(this.financeId, this.financeData).then(res => {
        this.loading = false;
        this.$message.success('修改成功');
        this.time = Date.parse(new Date()) / 1000;
        localStorage.setItem('isSuccess', true);
        localStorage.setItem('changeData', JSON.stringify(this.financeData));
        this.$router.push({
          name: 'dayAccount'
        });
      }, result => {
        this.loading = false;
        // this.$message.error(result.message);
      });
    },
    toSubmit() {
      if (!this.financeId) {
        this.loading = true;
        this.add();
      } else {
        this.loading = true;
        this.edit();
      }
    },
    paramObj(params, editForm) {
      for (const i in params) {
        if (i === 'incomeAmount') {
          params[i] = (editForm[i] * 100).toFixed(0);
        } else if (i === 'arrivalTime') {
          params[i] = editForm[i] / 1000;
        } else {
          params[i] = editForm[i];
        }
      }
      return params;
    },
    toSave(formValue) {
      this.paramObj(this.financeData, this.editFinanceForm);
      this.$refs[formValue].validate((vaild) => {
        if (vaild) {
          if (Number(this.financeData.incomeAmount) === 0) {
            ElMessage.error('收入金额不能为0');
            return;
          }
          if (isNaN(this.financeData.incomeAmount)) {
            ElMessage.error('请输入格式正确的流水金额');
            return;
          }
          this.toSubmit();
        } else {
          return false;
        }
      });
    },
    toClear() {
      localStorage.setItem('isSuccess', false);
      localStorage.setItem('changeData', '');
      this.$router.push({
        name: 'dayAccount'
      });
    },
    loadResourceSelect() {
      // 获取所属部门
      getDepartmentAll().then(res => {
        this.attributionMatrixList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    keyupEvent(value) {
      let str = value.replace(/[^\d-.]+/g, ''); // 只允许数字
      // str = str.replace(/^\d{10}$/, str.substring(0, str.length - 1)); // 出现第10位数值将它截取掉
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/\-{2,}/g, '-'); // 连续两个减号 replace为-
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^(\d*)\-(\d*)\-/g, '$1-$2');// 不连续减号 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后2位
      if (str.indexOf('.') < 0) {
        if (str.length > 16) {
          str = str.substr(0, str.length - 1);
        }
      } else {
        let integer = str.split('.')[0];
        const decimal = str.split('.')[1];
        if (integer.length > 16) {
          integer = integer.substr(0, integer.length - 1);
          str = integer + '.' + decimal;
        }
      }
      this.editFinanceForm.incomeAmount = str;
    }
  }
};
</script>
<style scoped lang="scss">
.create-finance {
 &::v-deep {
   .el-input {
     width: 240px;
   }
   .el-form-item{
     margin-bottom: 24px;
   }
   .el-input__inner,.el-textarea__inner {
     width: 240px;
   }
 }
 &.mobile-create {
  .lineHeightFlex {
    &::v-deep {
      .el-form-item__content {
        flex: 1;
      }
    }
  }
 }
}
</style>
<style lang="scss">
.createDayAccountwidth240 {
  width: 240px;
}
</style>
